using AutoMapper;
using lwzlz.Application.System.Dto;
using lwzlz.Common;
using lwzlz.Core;
using lwzlz.Core.Repository;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace lwzlz.Application.System
{
    public class ContractService
    {
        private readonly IRepository<Contract> _repository;

        public ContractService()
        {
            _repository = new Repository<Contract>();
        }

        #region 查询

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Contract Get(int id)
        {
            return _repository.Get(id);
        }

        /// <summary>
        /// 获取输出对象
        /// </summary>
        /// <typeparam name="TDto"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public TDto Get<TDto>(int id) where TDto : class, new()
        {
            var entity = Get(id);
            return Mapper.Map<TDto>(entity);
        }

        /// <summary>
        /// 分页数据
        /// </summary>
        /// <param name="dic_conditions"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<ContractOutput> GetListPage(
            int pageNumber, int rowsPerPage, Dictionary<string, string> dic_conditions, string field, string order, out int count)
        {
            #region 字段
            var select = @"
                t1.*,
                (t2.SchoolName+'('+t2.UserName+')') AS MemberName";
            #endregion

            #region 表
            var table = @"
	                Ser_Contract t1
                LEFT JOIN 
	                Ser_Member t2 
		                ON t2.Id=t1.MemberId";
            #endregion

            #region 参数查询

            string where = " t1.IsDeleted=0 ";

            //数据库参数
            Dictionary<string, object> dic = new Dictionary<string, object>();

            //用户ID
            if (dic_conditions.ContainsKey("MemberId") && dic_conditions["MemberId"] != null && dic_conditions["MemberId"] != "0")
            {
                var MemberId = dic_conditions["MemberId"];
                if (dic_conditions["MemberId"].ToString().Contains(","))
                {
                    var array = dic_conditions["MemberId"].ToString().Split(',');
                    MemberId = array[array.Length - 1].ToString();
                }
                dic.Add("@MemberId", MemberId);
                where += " AND t1.MemberId=@MemberId ";
            }
            //合同名称
            if (dic_conditions.ContainsKey("Name"))
            {
                dic.Add("@Name", dic_conditions["Name"]);
                where += " AND t1.Name=@Name ";
            }
            //合同编号
            if (dic_conditions.ContainsKey("Code"))
            {
                dic.Add("@Code", dic_conditions["Code"]);
                where += " AND t1.Code=@Code ";
            }

            #endregion

            #region 排序
            //排序sql语句拼接
            string orderby = " t1.CreationTime DESC ";//默认排序
            if (!string.IsNullOrWhiteSpace(field))
            {
                orderby = string.Format("{0} {1}", field, string.IsNullOrWhiteSpace(order) ? "DESC" : order);
            }

            #endregion

            var sql = $"SELECT {select} FROM {table} WHERE {where} ";

            var list = _repository.GetDynamicPaged(pageNumber, rowsPerPage, orderby, sql, dic);

            count = _repository.RecordQueryCount(sql, dic);

            return Mapper.Map<List<ContractOutput>>(list);
        }

        /// <summary>
        /// 获取查询结果行数
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public int GetListCount(string conditions, object param)
        {
            return _repository.RecordCount(conditions, param);
        }

        #endregion

        #region 编辑

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Add(ContractInput model)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                var entity = Mapper.Map<Contract>(model);
                entity.CreatorUserId = UserAuthentication.GetCurrentUser().UserID;
                entity.CreationTime = DateTime.Now;

                int? Id = _repository.Insert(entity, dbtran);

                dbtran.Commit();//提交事务
                return 1;
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Edit(ContractInput model)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                DateTime now = DateTime.Now;

                var entity = _repository.Get(model.Id, dbtran);
                Mapper.Map(model, entity);//把model数据转移到entity
                entity.LastModifierUserId = UserAuthentication.GetCurrentUser().UserID;
                entity.LastModificationTime = DateTime.Now;

                _repository.Update(entity, dbtran);
                dbtran.Commit();//提交事务
                return 1;
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="IdList"></param>
        /// <returns></returns>
        public void DeleteList(string IdList)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                foreach (string Id in IdList.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Contract model = _repository.Get(Id, dbtran);
                    model.IsDeleted = true;
                    _repository.Update(model, dbtran);
                }
                dbtran.Commit();//提交事务
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        #endregion
    }
}

